﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;

namespace DeviceMonitor.Utils
{
    public class RelayCommand : ICommand
    {
        private readonly Action<object> _execute; // 执行命令的逻辑
        private readonly Func<object, bool> _canExecute; // 判断命令是否可以执行的逻辑

        // 构造函数，接受执行命令和判断命令是否可以执行的委托
        public RelayCommand(Action<object> execute, Func<object, bool> canExecute = null)
        {
            _execute = execute ?? throw new ArgumentNullException(nameof(execute));
            _canExecute = canExecute;
        }

        // CanExecuteChanged 事件，用于通知命令状态是否改变
        public event EventHandler CanExecuteChanged
        {
            add => CommandManager.RequerySuggested += value;
            remove => CommandManager.RequerySuggested -= value;
        }

        // 判断命令是否可以执行
        public bool CanExecute(object parameter)
        {
            return _canExecute?.Invoke(parameter) ?? true; // 默认返回 true 表示可以执行
        }

        // 执行命令
        public void Execute(object parameter)
        {
            _execute(parameter);
        }
    }
}
